/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.util.ArrayList;

/**
 *
 * @author Jacek
 */
public class ClientsColector implements Runnable,ClientList {
    ArrayList<Client> clients;
     ArrayList<String> nameList;
    boolean active;

    public ClientsColector() {
        this.clients = new ArrayList<Client>();
        nameList=new ArrayList<String>();
        active=true;
    }
    public void Add(Client client){
        clients.add(client);
        nameList.add(client.GetName());
        client.setList(this);
        
    }
    @Override
    public void run() {
        while(active){
            for (Client client : clients) {              
                if(client.thread.getState()==Thread.State.TERMINATED){
                    clients.remove(client);
                    nameList.remove(client.GetName());
                }
            }   
        }
    }

    @Override
    public String getList() {
       String result="@list";
       for(String s : nameList)   
          result+=", "+s;
       
       return  result;
    }

    @Override
    public void SendTo(String name, String text) {
        for (Client client : clients) {
            if(client.GetName().equals(name))        
                client.send(text);
        }
    }

    @Override
    public void RemoveFromList(Client client) {
        nameList.remove(client.GetName());
        clients.remove(client);
    }
}
